﻿using TeamTasker.Client.Communication.TeamTaskerServiceReference;
using TeamTasker.Utils;

namespace TeamTasker.Client.Communication
{
    /// <summary>
    /// Provider of a proxy instance for TeamTasker Service.
    /// 
    /// PROXY USAGE RULES:
    /// 1.) On the client app startup init, e.g.: 
    ///         ServiceProxy.Init("http://localhost/TTService");
    ///         
    /// 2.) To call service methods, call ServiceProxy.Instance.*(...), e.g.:
    ///         ServiceProxy.Instance.Login(...);
    ///         ServiceProxy.Instance.GetTeamList(...);
    ///         ServiceProxy.Instance.GetTaskList(...);
    /// 
    /// 3.) On client application termination, shutdown the proxy:
    ///         ServiceProxy.Shutdown();
    ///         
    /// </summary>
    public class ServiceProxy
    {
        private static TeamTaskerServiceClient proxy = null;

        private ServiceProxy()
        {
        }

        public static void Init(string remoteAddress)
        {
            Validate.Null(proxy, "TeamTasker service proxy is already initialized");
            Validate.NotBlank(remoteAddress, "TeamTasker remote address is illegal: blank");

            if (!remoteAddress.EndsWith("/"))
            {
                remoteAddress += "/";
            }
            remoteAddress += "TeamTaskerService.svc";

            proxy = new TeamTaskerServiceClient(
                "WSDualHttpBinding_ITeamTaskerService", //"BasicHttpBinding_ITeamTaskerService", 
                remoteAddress);
        }

        public static void Shutdown()
        {
            if (proxy != null) 
            {
                proxy.Close();
                proxy = null;
            }
        }

        public static TeamTaskerServiceClient Instance
        {
            get { return proxy; }
        }
    }
}
